package com.xh.controller.api;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xh.mapper.BlogMapper;
import com.xh.pojo.Blog;
import com.xh.service.impl.ArticleServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/*
 * @author：Zero度
 * @2020/11/22 23:13
 * 文件说明：前端文章控制层
 * */
@RestController  // 返回字符串给前端
@RequestMapping("/api/")
public class ArticleController {

    @Autowired
    ArticleServiceImpl articleServiceImpl;

    Map<String, Object> map;

    /**
     * 获取按页数，条数获取文章
     * @param _t
     * @param p
     * @param size
     * @return
     */
    @RequestMapping(value = "article/list", produces = {"application/JSON;charset=utf-8"})
    public Map<String, Object> searchAllArticle(@RequestParam String _t, @RequestParam(defaultValue = "1") Integer p,
                                                @RequestParam Integer size, Integer cate_id){

        if (cate_id == null || cate_id == 0) {
            Page<Blog> blogPage = new Page<>(p,size);
            Map blogsMap = articleServiceImpl.allArticle(blogPage);

            //        model.addAttribute("all_article", blogs);

            map = new HashMap();
            map.put("data",blogsMap.get("data"));
            map.put("total",blogsMap.get("total"));
        }else{
            Page<Blog> blogPage = new Page<>(p,size);
            // 获取分类文章
            Map blogsMap = articleServiceImpl.getCateArticle(cate_id, blogPage);
            map = new HashMap();
            map.put("data",blogsMap.get("data"));
            map.put("total",blogsMap.get("total"));
        }
        map.put("code", 200);
        return map;

    }

    @Autowired
    BlogMapper blogMapper;

    /**
     * 根据id获取文章
     * @param articleId
     * @return
     */
    @RequestMapping(value = "article/{articleId}.html", method = RequestMethod.GET, produces = {"application/JSON;charset=utf-8"} )//
    public Map<String, Object> getArticleInfo(@PathVariable String articleId){
        Blog blog = blogMapper.selectById(articleId);
        map.put("code", 200);
        map.put("data", blog);
        String blogString = JSON.toJSONString(map); //被转义了
        blogString = blogString.replace("\\\\","\\");
        System.out.println(blogString);

        return map;
    }


}
